<?php
namespace app\index\controller;
use app\api\controller\Common;
use Carbon\Traits\ToStringFormat;
use think\Controller;
use think\Db;
use think\Loader;
use think\Model;
use think\exception;
use Carbon\Carbon;

class Instrument extends Controller
{
         private  $cdrq;
         private  $count;
         public function highblood()
            {
                return view();
            }
         public function dna()
            {
            return view();
            }

        public function microelement()
        {
            return view();
        }

        public function Imark(){
             return view();
        }

        public function UploadImark(){
            if (request()->ispost()) {
            $post = input('post.');
            $file = request()->file('TXT');
            if(empty($file)){
                $this->error('上传失败**不能为空','Instrument/imark');
            }
            $this->cdrq = request()->post('time');
            if(empty($this->cdrq)){
                $this->error('上传时间**不能为空','Instrument/imark');
            }
            $this->excel_importimark($file);
        }
    }
  

    public function excel_importimark($file){
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'Instrument');
        if (!$info) {
            $this->error('文件移动失败**','Instrument/imark');
        }
        //获取文件所在目录名
        $file_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'Instrument' .'\\'. $info->getSaveName();
        $filename = $info->getSaveName();
        //获取文件名后缀
        $suf = substr($filename, strrpos($filename, '.'));
        if ($suf !== '.txt') {
            $this->error('文件类型格式错误**请选择 .txt','Instrument/imark');
        }
        if(file_exists($file_path)){
            $str = file_get_contents($file_path);//将整个文件内容读入到一个字符串中
            $str = iconv("GBK","UTF-8",$str);
            $strs = explode("\r\n", $str);
        }
        $cc = explode("    ",$strs[0]);  
     
        // $xmdh = explode(":",($cc)[0])[4];
        for($i = 0;$i<count($strs);$i++){
            //遍历取到对应的项目流水号 + 项目测定值
            $data[] = (explode('        ', $strs[$i]));
        }
    
        foreach ($data as $key=>$val){
            try {
                $xmdh = explode("\t",$val[0])[2];
                $xmdh = explode(":", $xmdh)[1];
                $ybbh = explode("\t",$val[0])[1];
                $xmcdzod = trim(explode("\t",$val[0])[4]);
                $xmcdzbak = trim(explode("\t",$val[0])[3]);
                $xmcdz = mb_substr($xmcdzbak,3,5);
                $xmcdzcutoff = trim(explode("\t",$val[0])[5]);
                $cdrq =  $this->cdrq;
                $cdrq = date('Y-m-d H:i:s',strtotime($cdrq));
                
                if(strpos($xmdh,'HBsAg') !== false){
                    $xmdh =  '1001041';$jc='乙型肝炎病毒表面抗原测定';
                }
                if(strpos($xmdh,'CEA') !== false){
                    $xmdh =  '1000341';$jc='乙型肝炎病毒表面抗原测定';
                }
                if(strpos($xmdh,'AFP') !== false){
                    $xmdh =  '1000535';$jc='乙型肝炎病毒表面抗原测定';
                }
                if(strpos($xmdh,'HBsAb') !== false){
                    $xmdh =  '1001039';$jc='乙型肝炎病毒表面抗体测定';
                }
                if(strpos($xmdh,'HBeAg') !== false)
                {
                    $xmdh =  '1001037';$jc='乙型肝炎病毒e抗原测定';
                }
                if(strpos($xmdh,'HBeAb') !== false){
                    $xmdh =  '1001035';$jc='乙型肝炎病毒e抗体测定';
                }
                if(strpos($xmdh,'HBcAb') !== false){
                    $xmdh =  '1001043';$jc='乙型肝炎病毒核心抗体测定';
                }
                if (strpos($xmdh,'HEV-IgM') !== false){
                    $xmdh =  '1000903';$jc='戊型肝炎病毒抗体IgM测定-HEV-IgM';
                }
                if (strpos($xmdh,'HIV') !== false){
                    $xmdh =  '1000632';$jc = '人免疫缺陷病毒抗体测定';
                }
                if (strpos($xmdh,'HAV-IgM') !== false){
                    $xmdh =  '1000537';$jc = '甲型肝炎病毒抗体IgM测定';
                }
                if (strpos($xmdh,'HCV') !== false){
                    $xmdh =  '1000374';$jc ='丙型肝炎病毒抗体测定-HCV Ab';
                }
                if (strpos($xmdh,'HCV-Ab') !== false){
                    $xmdh =  '1000374';$jc ='丙型肝炎病毒抗体测定-HCV Ab';
                }
                if (strpos($xmdh,'TP') !== false){
                    $xmdh =  '1002375';$jc = '梅毒螺旋体抗体测定';
                }
                if (strpos($xmdh,'HAV') !== false){
                    $xmdh =  '300009';$jc = '甲型肝炎病毒抗体IgM测定';
                }
                if (strpos($xmdh,'HIV-Ab') !== false){
                    $xmdh =  '1000632';$jc = '甲型肝炎病毒抗体IgM测定';
                }
                $cdz = ['ITEMRESULT'=>$xmcdz,'CUTOFFVAL'=>$xmcdzcutoff,'ODVAL'=>$xmcdzod];
                $lisdata = Db::connect("database_cmlim")->table('EXAM_RESULT')->
                whereExp('TESTDATE',"=TO_DATE('$cdrq', 'YYYY-MM-DD HH24:MI:SS')")
                ->where('SAMPLENO',$ybbh)->where('ITEMCODE',$xmdh)->where('PLATFORMNAME','酶联免疫')->whereNotNull('ITEMRESULT')
                ->update($cdz);
                
                $int = Db::connect("database_cmlim")->table('EXAM_RESULT')->whereExp('TESTDATE',"=TO_DATE('$cdrq', 'YYYY-MM-DD HH24:MI:SS')")
                ->where('SAMPLENO',$ybbh)->where('ITEMCODE',$xmdh)->where('PLATFORMNAME','酶联免疫')->find();
               
                $int = Db::connect("database_cmlim")->execute("Declare
                                i_ExamResultId   Number := :ID;
                                i_IsForceRefresh Number := 0;
                                o_RetCode        Varchar2(1000) := '';
                                o_ErrMsg         Nvarchar2(1000) := '';
                            Begin
                                PKG_Exam.PR_CalcItemReference(i_ExamResultId,
                                                            i_IsForceRefresh,
                                                            o_RetCode,
                                                            o_ErrMsg);
                            End;",[
                    'ID'=>$int['ID'],
                ]);

            } catch (Exception $e) {
                continue;
                //echo $e->getMessage(); // 返回自定义的异常信息
            }
        }
             
        
        $cus = sizeof($data);
        //Model('Log')->addLog("导入了*.$cus.条的.$xmdh.记录,", 1,$cdrq);
        $this->success("导入成功*.$cus.条的记录.",'Instrument/imark');
       
}
  
    //开始执行更新结果
    // public function UpdataImarkByYbbhXmdh($ybbh,$cdrq,$xmdh,$xmcdz,$xmcdzcutoff,$xmcdzod){
    //     if(strpos($xmdh,'HBsAg') !== false){
    //         $xmdh =  '300001';$jc='乙型肝炎病毒表面抗原测定';
    //     }
    //     if(strpos($xmdh,'HBsAb') !== false){
    //         $xmdh =  '300002';$jc='乙型肝炎病毒表面抗体测定';
    //     }
    //     if(strpos($xmdh,'HBeAg') !== false)
    //     {
    //         $xmdh =  '300003';$jc='乙型肝炎病毒e抗原测定';
    //     }
    //     if(strpos($xmdh,'HBeAb') !== false){
    //         $xmdh =  '300004';$jc='乙型肝炎病毒e抗体测定';
    //     }
    //     if(strpos($xmdh,'HBcAb') !== false){
    //         $xmdh =  '300005';$jc='乙型肝炎病毒核心抗体测定';
    //     }
    //     if (strpos($xmdh,'HEV-IgM') !== false){
    //         $xmdh =  '1000903';$jc='戊型肝炎病毒抗体IgM测定-HEV-IgM';
    //     }
    //     if (strpos($xmdh,'HIV') !== false){
    //         $xmdh =  '300007';$jc = '人免疫缺陷病毒抗体测定';
    //     }
    //     if (strpos($xmdh,'HAV-IgM') !== false){
    //         $xmdh =  '1000537';$jc = '甲型肝炎病毒抗体IgM测定';
    //     }
    //     if (strpos($xmdh,'HCV') !== false){
    //         $xmdh =  '1000374';$jc ='丙型肝炎病毒抗体测定-HCV Ab';
    //     }
    //     if (strpos($xmdh,'TP-Ab') !== false){
    //         $xmdh =  '300052';$jc = '梅毒螺旋体抗体测定';
    //     }
    //     if (strpos($xmdh,'HAV') !== false){
    //         $xmdh =  '300009';$jc = '甲型肝炎病毒抗体IgM测定';
    //     }
    //     $data = ['PLATFORMNAME'=>'酶联免疫','cdrq'=>$cdrq,'SAMPLENO'=>$ybbh,'ITEMCODE'=>$xmdh];
    //     $cdz = ['xmcdz'=>$xmcdz,'xmcdzcutoff'=>$xmcdzcutoff,'xmcdzod'=>$xmcdzod];
    //     $lisdata = Db::table('EXAM_RESULT')->where($data)->update($cdz);
    //     // if(!$lisdata){
    //     //     return false;
    //     // }
    //     // return true;
    // }

    //处理上传的文件模块 excel----------222  ---------之前的excel 格式 --
    /*public function excel_importimark($file){
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info  = $file['Txt']->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel');
        if (!$info) {
            $this->error('文件移动失败**','Instrument/imark');
        }
        //获取文件所在目录名
        $file_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel' .'\\'. $info->getSaveName();
        //修改后缀

        //获取文件名后缀
        $suf = substr($file_path, strrpos($file_path, '.'));
        if ($info) {

            Loader::import('PHPExcel.PHPExcel');
            Loader::import('PHPExcel.PHPExcel.IOFactory.PHPExcel_IOFactory');
            //实例化PHPExcel类（注意：实例化的时候前面需要加'\'）
            // $objReader=new \PHPExcel_Reader_Excel5();
            if ($suf == '.xlsx') {
                $objReader = new \PHPExcel_Reader_Excel2007();
            } elseif ($suf == '.xls') {
                $objReader = new \PHPExcel_Reader_Excel5();
            } else {
                $this->error('文件类型错误**请选择 .xlsx***', 'Instrument/imark');
            }

            $objPHPExcel = $objReader->load($file_path); //获取excel文件
            $currentSheet = $objPHPExcel->getSheet(0);
            //获取总列数
            $allColumn = $currentSheet->getHighestColumn();
            //获取总行数
            $allRow = $currentSheet->getHighestRow();

            //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
            for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
                //从哪列开始，A表示第一列
                for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
                    //数据坐标
                    $address = $currentColumn . $currentRow;
                    //读取到的数据，保存到数组$data中
                    $cell = $currentSheet->getCell($address)->getValue();
                    if ($cell instanceof PHPExcel_RichText) {
                        $cell = $cell->__toString();
                    }
                    $data[$currentRow - 1][$currentColumn] = $cell;
                }
            }
            //获取下cutoff值
            $cutoff =  (explode('=', $objPHPExcel->getActiveSheet()->getCell('C2')->getValue()))[1];

            //获取下项目代号值
            $xmdh =  (explode('：', $objPHPExcel->getActiveSheet()->getCell('B2')->getValue()))[1];
            for($i=4;$i<=11;$i++){
                $c[] = array_combine($data[$i],$data[$i+10]);;
            }
            foreach (array_filter($c) as $k => $v) {
                foreach ($c[$k]  as $index => $value) {
                    if($index === ''){
                        unset($c[$k][$index]);
                    }

                    //开始遍历
                    if($this->UpdataImarkByYbbhXmdh($index,$this->cdrq,$xmdh,$value,$cutoff)){
                        continue;
                    }else{
                        continue;
                    }
                }
            }

            $cus = sizeof($c);
            Model('Log')->addLog("日期.{$this->cdrq}.Excel导入修改了一共**.999.**条*{$xmdh}.记录.", 1);

            $this->success("更新修改成功了一共**.999.**条*{$xmdh}", 'Instrument/imark');
        }
        else {
            $this->error("处理上传数据失败", 'Instrument/imark');
        }
    }*/


        


    /**
     * 微量元素6项导入
     * @date 2022-02-15
     * @author zAc 911606625@qq.com
     */
    public function microelementupload(){
        if (request()->ispost()) {
            $post = input('post.');
            $file = request()->file('excel');
            if(empty($file)){
                $this->error('上传失败**不能为空','Instrument/microelement');
            }
            $this->excel_imports($file);
        }
    }




    public function upload(){
             if (request()->ispost()) {
                 $post = input('post.');
                 $file = request()->file('txt');
                 if(empty($file)){
                     $this->error('上传失败**不能为空','Instrument/highblood');
                 }
                 $cc = request()->post('highbloodtime');
                 if(empty($cc)){
                     $this->error('上传时间**不能为空','Instrument/highblood');
                 }
                 $this->highbloodtime = $cc;
                 $this->excel_import($file);
             }
         }
         //处理上传的文件模块 excel
         public function excel_import($file){
             // 移动到框架应用根目录/public/uploads/ 目录下
             $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'Instrument');
             if (!$info) {
                 $this->error('文件移动失败**','Instrument/highblood');
             }
                 //获取文件所在目录名
                 $file_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'Instrument' .'\\'. $info->getSaveName();
                 $filename = $info->getSaveName();
                 //获取文件名后缀
                 $suf = substr($filename, strrpos($filename, '.'));
                 if ($suf !== '.txt') {
                     $this->error('文件类型格式错误**请选择 .txt','Instrument/highblood');
                 }
                 if(file_exists($file_path)){
                     $str = file_get_contents($file_path);//将整个文件内容读入到一个字符串中
                     $strs = explode("\r\n", $str);
                 }
                 $xmdh = trim(substr($strs[0],15,8));
                 for($i = 7;$i<count($strs);$i++){
                     //遍历取到对应的项目流水号 + 项目测定值
                     $data[] = (explode('--------', $strs[$i]));
                    }
                 foreach ($data as $key=>$val){
                     if($val[0] == ''){
                         break;
                     }
                      $xmdh = $xmdh;
                      $ybbh = trim($val[0]);
                      $xmcdz = trim(substr(($val[1]),0,7));
                      $xmcdz =  trim(str_replace('n','',$xmcdz));
                      $cdrq =  $this->highbloodtime;

                      $inserdata = ['xmdh'=>$xmdh,'ybbh'=>$ybbh,'xmcdz'=>$xmcdz,'cdrq'=>$cdrq,'createtime'=>date('Y-m-d h:i:s', time())];
                      $res = Db::table('xt_log_highblood')
                          ->data($inserdata)
                          ->insert();
                    }
                   if($res){

                       if($xmdh == 'AngⅠ-4'){
                          $newxmdh = 'AC30005';
                          $oldxmdh ='AngⅠ-4';
                      }

                   //这儿如果导入的是 -37的项目值  需要开始计算了
                 if($xmdh == 'AngⅠ-3'){
                     $newxmdh = 'AC30008';
                     $oldxmdh ='AngⅠ-3';
                     //考虑到后面要 计算 arr  这儿导入更新lis中 37 度的值
                     $this->InsertLisByhighblood37($cdrq,$newxmdh,$oldxmdh);

                     //开始计算 pra  肾素活性 的 值   修改检验目的代号 为 AC30007
                     $this->ShenHuoTolis($cdrq,$newxmdh = 'AC30007',$oldxmdh);
                     //开始计算  ARR 的值   修改检验目的代号 为  AC30009
                     $this->ARRTolis($cdrq,$newxmdh= 'AC30009',$oldxmdh = 'ARR');

                 }
                 if($xmdh == 'AngⅡ'){
                     $newxmdh = 'AC30006';
                     $oldxmdh ='AngⅡ';
                 }
                 if($xmdh == 'ALD' || $xmdh =='：ALD'){
                     $newxmdh = 'AC30004';
                     $oldxmdh ='ALD';
                 }
                  $this->InsertLisByhighblood($cdrq,$newxmdh,$oldxmdh);
             }
         }

        //单独导入  37的值  不进行跳转
        public function InsertLisByhighblood37($cdrq,$newxmdh,$oldxmdh){
        $aldres = Db::table('xt_log_highblood')->where(['cdrq'=>$cdrq])->whereLike('xmdh',$oldxmdh)->select();
        if($aldres){
            foreach ($aldres as $key=>$val){
                $res = $this->UpdataByYbbhXmdh($val['ybbh'],$cdrq,$newxmdh,$val['xmcdz']);
                if(!$res){
                    //执行失败 lis_xmcdz没有这个 继续执行
                    continue;
                }
            }
            $cus = sizeof($aldres);
            //Model('Log')->addLog("导入了*.$cus.条的.$oldxmdh.记录,日期.$cdrq", 1, $newxmdh);
        }
        else(
        $this->success("请确认是否导入成功,未查询到当前中间项目的信息,联系管理员.",'Instrument/highblood')
        );
    }
         //处理高血压项目导入lis   从数据库
         public function InsertLisByhighblood($cdrq,$newxmdh,$oldxmdh){
                //先导入ALD
             /***
              * AC30004	醛固酮
             AC30005	血管紧张素 I
             AC30006	血管紧张素 II
             AC30007	肾素活性
              */
             $aldres = Db::table('xt_log_highblood')->where(['cdrq'=>$cdrq])->whereLike('xmdh',$oldxmdh)->select();
             if($aldres){
                 foreach ($aldres as $key=>$val){
                    $res = $this->UpdataByYbbhXmdh($val['ybbh'],$cdrq,$newxmdh,$val['xmcdz']);
                    if(!$res){
                        //执行失败 lis_xmcdz没有这个 继续执行
                        continue;
                    }
                 }
                 $cus = sizeof($aldres);
                 Model('Log')->addLog("导入了*.$cus.条的.$oldxmdh.记录,日期.$cdrq", 1, $newxmdh);
                 $this->success("导入成功.$cus.条的.$oldxmdh.记录",'Instrument/highblood');
             }
             $this->success("请确认是否导入成功,未查询到当前中间项目的信息,联系管理员.",'Instrument/highblood');
         }


         //开始计算肾素活性值为选择日期当天的 37度－4度的值***
         public function ShenHuoTolis($cdrq,$newxmdh,$oldxmdh){
              $n37 = Db::table('xt_log_highblood')->where(['xmdh'=>'AngⅠ-3','cdrq'=>$cdrq])->select();
              $n4  = Db::table('xt_log_highblood')->where(['xmdh'=>'AngⅠ-4','cdrq'=>$cdrq])->select();
              foreach ($n37 as $key=>$val){
                  /*var_dump($val['xmcdz']);*/
                  foreach ($n4 as $key4=>$valn4){
                      /*var_dump($valn4['xmcdz']);exit();*/
                      if($val['ybbh'] ==$valn4['ybbh']){
                          $endxmcdz = $val['xmcdz']-$valn4['xmcdz'];
                          $this->UpdataByYbbhXmdh($val['ybbh'],$cdrq,$newxmdh,$endxmcdz);
                          //这儿把 肾素活性的值 导入 到 lis 了

                          //这儿还要把 这个 肾素活性的值 加入到 xt_log_highblood  方便后面的 arr 计算
                          //$cdrq =  $this->highbloodtime;
                          $inserdataARR = ['xmdh'=>'PRA','ybbh'=>$val['ybbh'],'xmcdz'=>$endxmcdz,'cdrq'=>$cdrq,'createtime'=>date('Y-m-d h:i:s', time())];
                          $res = Db::table('xt_log_highblood')
                              ->data($inserdataARR)
                              ->insert();
                      }
                      continue;
                  }
                  continue;
              }
              $cus = sizeof($n37);
              Model('Log')->addLog("计算导入了*.$cus.条.$oldxmdh.的记录,日期.$cdrq", 1, $oldxmdh);
            //这儿开始计算  高血压 四项 外加的 两项目 值
            //$this->success("导入成功*.$cus.条.$oldxmdh.肾活素的记录.$oldxmdh.",'Instrument/highblood');
        }


        //开始计算 ARR 的 值 ***
         public function ARRTolis($cdrq,$newxmdh,$oldxmdh){
        $ALD  = Db::table('xt_log_highblood')->where(['xmdh'=>'ALD','cdrq'=>$cdrq])->select();
        $PRA = Db::table('xt_log_highblood')->where(['xmdh'=>'PRA','cdrq'=>$cdrq])->select();
        foreach ($ALD as $key=>$val){
            /*var_dump($val['xmcdz']);*/
            foreach ($PRA as $keyPRA=>$valPRA){
                /*var_dump($valn4['xmcdz']);exit();*/
                if($val['ybbh'] ==$valPRA['ybbh']){
                    //这儿开始计算
                    if($valPRA['xmcdz']*10 == 0){
                        $this->success("计算过程中有除数为 0 的结果 请修改联系管理员.",'Instrument/highblood');
                    }
                    $endxmcdz = $val['xmcdz']/($valPRA['xmcdz']*10);
                    $this->UpdataByYbbhXmdh($val['ybbh'],$cdrq,$newxmdh,$endxmcdz);
                }
                continue;
            }
            continue;
        }
        $cus = sizeof($PRA);
        Model('Log')->addLog("计算导入了*.$cus.条.$oldxmdh.ARR的记录,日期.$cdrq", 1, $oldxmdh);
        //这儿开始计算  高血压 四项 外加的 两项目 值
        $this->success("导入成功*.$cus.条.$oldxmdh.肾活素的记录.$oldxmdh.",'Instrument/highblood');
    }

         //开始执行更新结果
         public function UpdataByYbbhXmdh($ybbh,$cdrq,$xmdh,$xmcdz){
             //流水号判断下子
             if($ybbh < 10){
                 $ybbh = '40'.$ybbh;
             }else {
                 $ybbh = '4' . $ybbh;
             }
             $data = ['yqdh'=>'IMARK','cdrq'=>$cdrq,'ybbh'=>$ybbh,'xmdh'=>$xmdh];
             $lisdata = Db::table('lis_xmcdz')->where($data)->data('xmcdz',$xmcdz)->update();
             if(!$lisdata){
                 return false;
             }
             return true;
         }

    /**
     * 病理 DNA 信息导入
     */
         public function DnaSearch(){
            //查询项目里面的
             $ybid = $_POST['ybid'];
             if(empty($ybid)){
                 $this->error('不能为空','Instrument/dna');
             }
             //开始查询
             //$res= Db::query("select * from  dbo.lis_ybxx where yqdh = '病理' and ybid = :ybid  and jymddm = ',AC300044,'",['ybid'=>$ybid]);

             $res= Db::query("select * from  dbo.lis_ybxx where yqdh = '病理' and ybid = :ybid  and jymd like '%DNA倍体分析%'",['ybid'=>$ybid]);

             if(!$res){
                 $this->error('未查询到当前的条码号的 ***DNA倍体分析**','Instrument/dna');
             }
             foreach ($res as $cout){
                 $data = $cout;
                 $data['ybbh'] = 'P'.$data['ybbh'];
                 if($data['brxb'] == '/' || $data['brnl'] == '/'){
                     $this->error('请在样本检验界面修改该信息的**性别 ** 姓名 不能为 **/*** 请修改','Instrument/dna');
                 }
                 //判断 他们是  1 男 0 女
                 if($data['brxb'] == 2){
                     $data['brxb'] = 0;
                 }
             }
             //连接 dna库  查询是否重复导入了
             //$data = Db::connect("database_bldna")->table("DtPatient")->select();
             $result = Db::connect("database_bldna")->execute('DECLARE @RC int
DECLARE @user_id int=124002
DECLARE @name nvarchar(50)=?
DECLARE @gender bit=?
DECLARE @age smallint=?
DECLARE @identifier varchar(20)=?
DECLARE @medical_insurance_no varchar(50)
DECLARE @nationality nvarchar(20)
DECLARE @menses datetime
DECLARE @tele_phone nvarchar(30)
DECLARE @mobile_phone nvarchar(30)=?
DECLARE @addr nvarchar(200)
DECLARE @addr_code nvarchar(15)
DECLARE @company nvarchar(200)
DECLARE @birth_place nvarchar(50)
DECLARE @profession nvarchar(50)
DECLARE @no nvarchar(20)=?
DECLARE @category nvarchar(4)=?
DECLARE @extra_no nvarchar(20)
DECLARE @specimen int=1
DECLARE @specimen_no nvarchar(20) =?
DECLARE @date datetime=?
DECLARE @hospital nvarchar(100)=?
DECLARE @department nvarchar(40)=?
DECLARE @doctor nvarchar(50)=?
DECLARE @out_no nvarchar(20)
DECLARE @in_no nvarchar(20)
DECLARE @area nvarchar(10)
DECLARE @bed_no nvarchar(10)
DECLARE @barcode nvarchar(20)=?
DECLARE @remark nvarchar(500)=?
DECLARE @dna_id uniqueidentifier=0x0
DECLARE @tbs_id uniqueidentifier=0x0
DECLARE @cyto_id uniqueidentifier=null
DECLARE @biopsy_time datetime
DECLARE @biopsy_result nvarchar(1000)
DECLARE @biopsy_hospt nvarchar(100)
DECLARE @accept_sms bit=0
DECLARE @married bit=1
DECLARE @clinical_diagnosis nvarchar(500)
DECLARE @id uniqueidentifier
DECLARE @age_base tinyint=0
EXECUTE @RC = [nhis3_湖北省武汉市千麦医学检验实验室].[dbo].[InsPatientRegistration] 
   @user_id
  ,@name
  ,@gender
  ,@age
  ,@identifier
  ,@medical_insurance_no
  ,@nationality
  ,@menses
  ,@tele_phone
  ,@mobile_phone
  ,@addr
  ,@addr_code
  ,@company
  ,@birth_place
  ,@profession
  ,@no
  ,@category
  ,@extra_no
  ,@specimen
  ,@specimen_no
  ,@date
  ,@hospital
  ,@department
  ,@doctor
  ,@out_no
  ,@in_no
  ,@area
  ,@bed_no
  ,@barcode
  ,@remark
  ,@dna_id
  ,@tbs_id
  ,@cyto_id
  ,@biopsy_time
  ,@biopsy_result
  ,@biopsy_hospt
  ,@accept_sms
  ,@married
  ,@clinical_diagnosis
  ,@id OUTPUT
  ,@age_base
',[$data['brxm'],$data['brxb'],$data['brnl'],$data['idnumber'],$data['brphone'],$data['ybbh'],'检测中心',$data['ybbh'],$data['cyrq'],$data['byh'],'妇科','',$data['ybid'],'条码'.$data['ybid'].'流水号'.$data['ybbh']]);
             //开始记录日志
             Model('Log')->addLog("导入了一条**dna贝体项目**记录*".$data['ybid'], 1, $data['ybid']);
             $this->success('导入成功 ** 请软件刷新查看','Instrument/dna');
         }


    public function Inheritance()
    {
        return view();
    }

    /***
     *   遗传 信息 导入
     */
    public function InheritanceSearch(){
        //查询项目里面的
        $ybid = $_POST['ybid'];
        if(empty($ybid)){
            $this->error('不能为空','Instrument/Inheritance');
        }

      /*  $res= Db::query("select * from  dbo.lis_ybxx where yqdh = '病理' and ybid = :ybid  and jymd like '%DNA倍体分析%'",['ybid'=>$ybid]);*/
         $res= Db::query("select * from  dbo.lis_ybxx where yqdh = '遗传' and ybid = :ybid",['ybid'=>$ybid]);

        if(!$res){
            $this->error('未查询到当前的条码号的 ***Inheritance记录信息 请确认是否接入样本检验**','Instrument/Inheritance');
        }
        foreach ($res as $cout){
            $data = $cout;
            if($data['brxb'] == '/' || $data['brnl'] == '/'){
                $this->error('请在样本检验界面修改该信息的**性别 ** 姓名 不能为 **/*** 请修改','Instrument/dna');
            }
            //判断 他们是  1 男 0 女
            if($data['brxb'] == 1){
                $data['brxb'] = '男';
            }elseif ($data['brxb'] == 2){
                $data['brxb'] = '女';
            }
        }

        /*dd($data);
        exit();*/
        //连接 dna库  查询是否重复导入了
        //$data = Db::connect("database_bldna")->table("DtPatient")->select();
        $result = Db::connect("database_yc")->execute("replace INTO  `t_patientinfo` VALUES (:id, :name, :brxb, :age, '', '', '', '', 
'', '', '', '', '', '', '', '', '', '', :ybid, '', '', 0, 
'1', '1', '1', '1', '1', '1', '1', 'zAc', 0, 0, 0,'','','','','','','','','','')",['id'=>$data['ybbh'],
            'name'=>$data['brxm'],'brxb'=>$data['brxb'],'age'=>$data['brnl'],'ybid'=>$data['ybid']]);
        //开始记录日志
        Model('Log')->addLog("单个导入了一条**染色体400带项目**记录*".$data['ybid'], 1, $data['ybid']);
        $this->success('导入成功 ** 请软件刷新查看','Instrument/Inheritance');
    }

    /**
     * 批量 根据 检验日期 批量导入
     */
    /***
     *   遗传 信息 导入
     */
    public function InheritanceSearchAllByCdrq(){
        //查询项目里面的
        $cdrq = $_POST['cdrq'];
        if(empty($cdrq)){
            $this->error('不能为空','Instrument/Inheritance');
        }

        /*  $res= Db::query("select * from  dbo.lis_ybxx where yqdh = '病理' and ybid = :ybid  and jymd like '%DNA倍体分析%'",['ybid'=>$ybid]);*/
        /*$res= Db::query("select * from  dbo.lis_ybxx where yqdh = '遗传'
                              and jymd  like '%外周血染色体核型分析400带%' and cdrq > :cdrq ",['cdrq'=>$cdrq]);*/
        $res= Db::query("select * from  dbo.lis_ybxx where yqdh = '遗传' 
                              and  cdrq > :cdrq ",['cdrq'=>$cdrq]);
        if(!$res){
            $this->error('未查询到当前的条码号的 ***Inheritance记录信息 请确认是否接入样本检验**','Instrument/Inheritance');
        }
        foreach ($res as $cout){
            $data = $cout;
            //判断 他们是  1 男 0 女
            if($data['brxb'] == 1){
                $data['brxb'] = '男';
            }elseif ($data['brxb'] == 2){
                $data['brxb'] = '女';
            }
            $result = Db::connect("database_yc")->execute("replace INTO `t_patientinfo` VALUES (:id, :name, :brxb, :age, '', '', '', '', 
'', '', '', '', '', '', '', '', '', '', :ybid, '', '', 0, 
'1', '1', '1', '1', '1', '1', '1', 'zAc', 0, 0, 0,'','','','','','','','','','')",['id'=>$data['ybbh'],
                'name'=>$data['brxm'],'brxb'=>$data['brxb'],'age'=>$data['brnl'],'ybid'=>$data['ybid']]);
        }
        $cus = sizeof($res);
        //开始记录日志
        Model('Log')->addLog("批量导入了**.$cus.**条**检验日期大于*.$cdrq.*染色体400带项目**记录*".$data['ybid'], 1, $data['ybid']);
        $this->success("导入成功 *.$cus.条记录* 请软件刷新查看",'Instrument/Inheritance');
    }



    /**
     *   GM导入
     */
    public function Gmimport(){
        return view();
    }

    public function UploadGm(){
        if (request()->ispost()) {
            $post = input('post.');
            $file    = request()->file('');
            if(empty($file)){
                $this->error('上传失败**不能为空','Instrument/Gmimport');
            }
            $cc = request()->post('time');
            if(empty($cc)){
                $this->error('上传时间**不能为空','Instrument/Gmimport');
            }
            //$this->highbloodtime = $cc;
            $this->excel_importGm($file);
        }
    }
    //处理上传的文件模块 excel
    public function excel_importGm($file){
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file['Txt']->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'Instrument');
        if (!$info) {
            $this->error('文件移动失败**','Instrument/highblood');
        }
        //获取文件所在目录名
        $file_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'Instrument' .'\\'. $info->getSaveName();

        $filename = $info->getSaveName();
        //获取文件名后缀
        $suf = substr($filename, strrpos($filename, '.'));
        if ($suf !== '.Txt') {
            $this->error('文件类型格式错误**请选择 .Txt','Instrument/Gmimport');
        }

        if(file_exists($file_path)){
            $str = file_get_contents($file_path);//将整个文件内容读入到一个字符串中
            $str = iconv("gb2312", "utf-8//IGNORE",$str);
            $strs = explode("\r\n", $str);
        }

        $xmdh = trim(substr($strs[1],18,8));

        if($xmdh  === 'GM试验'){
            $xmdh = 'S00002';
            $xmmc = 'GM试验(夹心法)';
        }else{
            $xmdh = 'S00001';//G试验
            $xmmc = 'G试验';
        }
        for($i = 9;$i<count($strs);$i++){
            //遍历取到对应的项目流水号 + 项目测定值
            $data[] = (explode('	', $strs[$i]));
        }
        foreach ($data as $key=>$val) {
            //删除为空的数组
            error_reporting(E_ERROR | E_WARNING | E_PARSE);
            if( !$key ){
                unset( $data[$key] );
            }
            if (preg_match('/[a-zA-Z]/',$val['2']) || empty($val['2'])){
                continue;
            }
            $ybbh = $val['2'];
            $cdrq = date('Y-m-d', time());
            $xmcdz = $val['5'];
            //这里按专业组加个判断 如果小于 37.5

            if($xmdh == 'S00001' && $xmcdz < 37.5){
                $xmcdz = '<37.5';
            }

           /* echo ''.$xmdh.'---'. $xmmc.$ybbh.'--'.$xmcdz.'||||';*/

            $res = $this->UpdataGmByYbbhXmdh($ybbh,$cdrq,$xmdh,$xmcdz);
            if(!$res){
                 continue;//执行失败 lis_xmcdz没有这个 继续执行
                     }
            }
        /*exit();*/
            $cus = sizeof($data);
            Model('Log')->addLog("导入了*.$cus.条的.$xmmc.记录,日期.$cdrq", 1, $xmdh);
            $this->success("导入成功.$cus.条的.$xmmc.记录",'Instrument/Gmimport');
        }
        //开始执行更新GM结果
        public function UpdataGmByYbbhXmdh($ybbh,$cdrq,$xmdh,$xmcdz){
                //流水号判断下子
                $data = ['yqdh'=>'IMARK','cdrq'=>$cdrq,'ybbh'=>$ybbh,'xmdh'=>$xmdh];
                $lisdata = Db::table('lis_xmcdz')->where($data)->data('xmcdz',$xmcdz)->update();
                if(!$lisdata){
                    return false;
                }
                return true;
        }


    /**
     *   内毒素导入
     */
    public function Endotoxinimport(){
        return view();
    }

    public function UploadEndotoxin(){
        if (request()->ispost()) {
            $post = input('post.');
            $file    = request()->file('');
            if(empty($file)){
                $this->error('上传失败**不能为空','Instrument/Gmimport');
            }
            $cc = request()->post('time');
            if(empty($cc)){
                $this->error('上传时间**不能为空','Instrument/Gmimport');
            }
            //$this->highbloodtime = $cc;
            $this->excel_importEndotoxin($file);
        }
    }
    //处理上传的文件模块 excel
    public function excel_importEndotoxin($file){
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file['Txt']->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'Instrument');
        if (!$info) {
            $this->error('文件移动失败**','Instrument/highblood');
        }
        //获取文件所在目录名
        $file_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'Instrument' .'\\'. $info->getSaveName();

        $filename = $info->getSaveName();
        //获取文件名后缀
        $suf = substr($filename, strrpos($filename, '.'));
        if ($suf !== '.Txt') {
            $this->error('文件类型格式错误**请选择 .Txt','Instrument/Gmimport');
        }

        if(file_exists($file_path)){
            $str = file_get_contents($file_path);//将整个文件内容读入到一个字符串中
            $str = iconv("gb2312", "utf-8//IGNORE",$str);
            $strs = explode("\r\n", $str);
        }
        //$xmdh = trim(substr($strs[1],18,16));

        for($i = 9;$i<count($strs);$i++){
            //遍历取到对应的项目流水号 + 项目测定值
            $data[] = (explode('	', $strs[$i]));
        }
        foreach ($data as $key=>$val) {
            //删除为空的数组
            error_reporting(E_ERROR | E_WARNING | E_PARSE);
            if( !$key ){
                unset( $data[$key] );
            }
            if (preg_match('/[a-zA-Z]/',$val['2']) || empty($val['2'])){
                continue;
            }
            $ybbh = $val['2'];
            $cdrq = date('Y-m-d', time());
            $xmcdz = $val['5'];

            //echo $ybbh.'---'.$xmcdz.'|||';
            $res = $this->UpdataGmByYbbhXmdh($ybbh,$cdrq,$xmdh = "IM00101",$xmcdz);
            if(!$res){
                continue;//执行失败 lis_xmcdz没有这个 继续执行
            }
        }
        $cus = sizeof($data);
        Model('Log')->addLog("导入了*.$cus.条的.内毒素(透析液)*.记录,日期.$cdrq", 1, $xmdh);
        $this->success("导入成功.$cus.条的.$xmdh.记录",'Instrument/Endotoxinimport');
    }

    /***
     * 微生物耐药表型
     */
    public function wswdrugresistance(){
        return view();
    }

    public function wswDrugresistanceImport(){
        $ybbh = $_POST['ybbh'];
        $res = implode('， ',$_POST['AC']);

        /*if(empty($ybbh) || empty($res) ){
            $this->error('不能为空','Instrument/wswDrugresistance');
        }*/
        if(empty($ybbh)){
            $this->error('条码不能不能为空','Instrument/wswDrugresistance');
        }
       /* $cc = Db::table(' xj_ybxx ')->where('ybbh',$ybbh)->data('fullname',$res)->update();*/
        $byh = Db::table('xj_ybxx')->where('ybbh',$ybbh)->find();

        $cc = Db::execute("update xj_ybxx set fullname = :fullname where ybbh = :ybbh",['fullname'=>$res,
        'ybbh'=>$ybbh]);
        if($cc){
            //更新成功 开始重新生成
            Model('Common')->ModifyReportStatus($byh['byh']);

            Model('Log')->addLog("导入了一条微生物条码为.$ybbh.的记录,表型:.$res.", 1, $ybbh);
            $this->success('修改成功** 更新报告成功','Instrument/wswDrugresistance');
        }
        $this->error('修改失败','Instrument/wswDrugresistance');
    }




}